import smtplib
import time
from email.mime.text import MIMEText
from email.header import Header
import logging


def send_email(mainSeting, setting, params):
    """
    发送邮件
    """
    # 发送等级为ALL无更新也发送，非ALL只发送有更新的
    level = setting['MAIL_RECEIVER_LEVEL']
    if level != "ALL" and len(params['domain']) == 0:
        return True
    servName = mainSeting['appName']
    if servName is None or servName == "":
        servName = '未命名'

    Time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    sslLen = len(params['domain'])
    domainList = "</p></p>".join(params['domain'])
    runLogs = "</p></p>".join(params['logs'])
    body = f"""
    <p>尊敬的管理员：</p>
    <p>{Time} 任务运行结束，检查到需要更新的节点数量为{sslLen}个。</p>
    <p>更新的域名：</p>
    <p>{domainList}</p>
    <p>运行日志：</p>
    <p>{runLogs}</p>
    """
    message = MIMEText(body, 'html', 'utf-8')
    message['From'] = Header(setting['MAIL_USER'])  # qq邮箱不能声明utf-8
    message['To'] = Header(setting['MAIL_RECEIVER'], 'utf-8')

    subject = f"{servName} {Time} SSL自动部署{sslLen}个"
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(setting['MAIL_HOST'], int(setting['MAIL_PORT']))
        smtpObj.login(setting['MAIL_USER'], setting['MAIL_PASS'])
        smtpObj.sendmail(setting['MAIL_SENDER'],
                         setting['MAIL_RECEIVER'], message.as_string())
        return True
    except Exception as error:
        # 错误 message
        print(error)
        logging.error(error)
        return False
